import { Injectable } from '@nestjs/common';
import { CreateCommentDto } from './dto/create-comment.dto';
import { UpdateCommentDto } from './dto/update-comment.dto';
import { BusinessException } from '../../common/exceptions/business.exception';
import { InjectRepository } from '@nestjs/typeorm';
import { Comment } from './entities/comment.entity';
import { Repository } from 'typeorm';
import { Article } from '../article/entities/article.entity';
import { User } from '../user/entities/user.entity';
@Injectable()
export class CommentService {
  constructor(@InjectRepository(Comment) private readonly comment: Repository<Comment>,
    @InjectRepository(Article) private readonly article: Repository<Article>,
    @InjectRepository(User) private readonly user: Repository<User>) { }
  findAllbyarticle(articleid: any) {
    return this.comment.find({
      where: { article: { articleid: articleid.articleid } },
      relations: ['user'],
    })
  }
  findAllbyuser(articleid: any) {
       return this.comment.find({
      where: { user: { userid: articleid.userid } },
      relations: ['article'],
    })
  }
  async create(createCommentDto: CreateCommentDto) {
    
    const user = await this.user.findOne({ where: { userid: createCommentDto.userid } });
    if (!user) throw new Error('用户不存在');
    const article = await this.article.findOne({ where: { articleid: createCommentDto.articleid } });
    if (!article) throw new Error('文章不存在');
    const comment = this.comment.create({ ...createCommentDto, user, article });
    return this.comment.save(comment);
  }

  findAll() {
    return `This action returns all comment`;
  }

  findOne(id: number) {
    return `This action returns a #${id} comment`;
  }

  update(id: number, updateCommentDto: UpdateCommentDto) {
    return `This action updates a #${id} comment`;
  }

  remove(id: string) {
    return this.comment.delete(id);
  }
}
